<template>
  <view class="generate-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-content">
        <text class="nav-title">生成题目</text>
        <button class="help-btn" @click="showHelp">
          <text class="iconfont icon-help"></text>
          帮助
        </button>
      </view>
    </view>

    <!-- 主内容区域 -->
    <view class="main-content">
      <!-- 输入方式选择 -->
      <view class="section first-section">
        <text class="section-title">选择输入方式</text>
        <view class="input-methods">
          <view 
            v-for="method in inputMethods" 
            :key="method.id"
            class="method-item"
            :class="{ active: currentMethod === method.id }"
            @click="selectMethod(method.id)"
          >
            <text class="iconfont" :class="method.icon"></text>
            <text class="name">{{ method.name }}</text>
            <text class="desc">{{ method.desc }}</text>
          </view>
        </view>
      </view>

      <!-- 手动输入区域 -->
      <view v-if="currentMethod === 1" class="section">
        <view class="section-header">
          <text class="section-title">输入汉字</text>
          <text class="input-count">已输入: {{ inputText.length }}/6</text>
        </view>
        <input 
          class="char-input"
          type="text"
          v-model="inputText"
          placeholder="请输入要学习的汉字"
          maxlength="6"
        />
      </view>

      <!-- 单元选择区域 -->
      <view v-if="currentMethod === 2" class="section">
        <view class="section-header">
          <text class="section-title">选择单元</text>
          <text class="unit-range">1-60单元</text>
        </view>
        <view class="unit-selector">
          <button class="minus" @click="decreaseUnit">-</button>
          <input 
            type="number"
            v-model="unitNumber"
            class="unit-input"
            @input="checkUnitRange"
          />
          <button class="plus" @click="increaseUnit">+</button>
        </view>
      </view>

      <!-- 拍照识别区域 -->
      <view v-if="currentMethod === 3" class="section">
        <view class="section-header">
          <text class="section-title">拍照识别</text>
          <button v-if="photoUrl" class="retake-btn" @click="retakePhoto">重新拍照</button>
        </view>
        <view class="photo-area" @click="takePhoto">
          <image v-if="photoUrl" :src="photoUrl" mode="aspectFill" class="preview"/>
          <view v-else class="placeholder">
            <text class="iconfont icon-camera"></text>
            <text class="tip">点击拍照识别汉字</text>
          </view>
        </view>
      </view>

      <!-- 参数设置 -->
      <view class="section">
        <text class="section-title">难度选择</text>
        <view class="difficulty-options">
          <button 
            v-for="level in difficultyLevels"
            :key="level.id"
            class="difficulty-btn"
            :class="{ active: currentDifficulty === level.id }"
            @click="selectDifficulty(level.id)"
          >
            {{ level.name }}
          </button>
        </view>
      </view>

      <view class="section">
        <text class="section-title">语言风格</text>
        <view class="style-options">
          <button 
            v-for="style in styleOptions"
            :key="style.id"
            class="style-btn"
            :class="{ active: currentStyle === style.id }"
            @click="selectStyle(style.id)"
          >
            {{ style.name }}
          </button>
        </view>
      </view>

      <!-- 生成按钮 -->
      <view class="generate-btn-wrapper">
        <button class="generate-btn" @click="handleGenerate">
          开始生成
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { generateExercise } from '@/api/exercise'

// 输入方式
const inputMethods = [
  { 
    id: 1, 
    name: '手动输入', 
    desc: '限6个汉字',
    icon: 'icon-keyboard' 
  },
  { 
    id: 2, 
    name: '单元选择', 
    desc: '1-60单元',
    icon: 'icon-list' 
  },
  { 
    id: 3, 
    name: '拍照识别', 
    desc: '自动识别',
    icon: 'icon-camera' 
  }
]

// 难度等级
const difficultyLevels = [
  { id: 1, name: '容易' },
  { id: 2, name: '中等' },
  { id: 3, name: '较难' }
]

// 语言风格
const styleOptions = [
  { id: 1, name: '标准' },
  { id: 2, name: '趣味' },
  { id: 3, name: '文学' }
]

// 响应式状态
const currentMethod = ref(1)
const currentDifficulty = ref(1)
const currentStyle = ref(1)
const inputText = ref('')
const unitNumber = ref(1)
const photoUrl = ref('')

// 选择输入方式
const selectMethod = (id) => {
  currentMethod.value = id
}

// 选择难度
const selectDifficulty = (id) => {
  currentDifficulty.value = id
}

// 选择风格
const selectStyle = (id) => {
  currentStyle.value = id
}

// 单元数字增减
const decreaseUnit = () => {
  if (unitNumber.value > 1) {
    unitNumber.value--
  }
}

const increaseUnit = () => {
  if (unitNumber.value < 60) {
    unitNumber.value++
  }
}

const checkUnitRange = () => {
  let num = parseInt(unitNumber.value)
  if (num < 1) num = 1
  if (num > 60) num = 60
  unitNumber.value = num
}

// 拍照相关
const takePhoto = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera'],
    success: (res) => {
      photoUrl.value = res.tempFilePaths[0]
    }
  })
}

const retakePhoto = () => {
  photoUrl.value = ''
}

// 生成题目
const handleGenerate = async () => {
  try {
    // 参数校验
    if (currentMethod.value === 1 && !inputText.value) {
      return uni.showToast({
        title: '请输入汉字',
        icon: 'none'
      })
    }

    // 构建请求参数
    const params = {
      type: currentMethod.value,
      difficulty: currentDifficulty.value,
      style: currentStyle.value
    }

    // 根据不同输入方式添加参数
    if (currentMethod.value === 1) {
      params.chars = inputText.value
    } else if (currentMethod.value === 2) {
      params.unit_id = unitNumber.value
    } else if (currentMethod.value === 3 && photoUrl.value) {
      // 如果是拍照模式，先上传图片
      console.log('开始上传图片')
      const uploadRes = await uni.request({
        url: 'https://paintasong.cn/api/oss/upload/signed-url',
        method: 'GET',
        data: {
          dir: 'exercise',
          filename: `${Date.now()}.jpg`
        },
        header: {
          'Authorization': 'Bearer ' + uni.getStorageSync('token')
        }
      })

      console.log('获取上传URL响应:', uploadRes.data)

      if (uploadRes.data.code === 0) {
        // 上传图片到 OSS
        const uploadResult = await uni.uploadFile({
          url: uploadRes.data.data.signedUrl,
          filePath: photoUrl.value,
          name: 'file'
        })
        
        console.log('图片上传结果:', uploadResult)
        params.image_url = uploadRes.data.data.signedUrl
      } else {
        throw new Error('图片上传失败')
      }
    }

    console.log('生成题目请求参数:', params)

    // 调用生成接口
    const res = await uni.request({
      url: 'https://paintasong.cn/api/exercise/generate',
      method: 'POST',
      data: params,
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token'),
        'Content-Type': 'application/json'
      }
    })
    
    console.log('生成题目响应:', res.data)
    
    if (res.data.code === 0) {
      const exerciseData = res.data.data
      console.log('生成成功，完整响应数据:', JSON.stringify(exerciseData, null, 2))
      
      // 构造学习页面需要的数据格式
      const processedData = {
        id: exerciseData.id,
        baseChars: exerciseData.baseChars || inputText.value.split(''),
        content: {
          level_1: exerciseData.content?.level_1 || [],
          level_2: exerciseData.content?.level_2 || [],
          level_3: exerciseData.content?.level_3 || [],
          level_4: exerciseData.content?.level_4 || []
        },
        audioUrl1: exerciseData.audioUrl1 || '',
        audioUrl2: exerciseData.audioUrl2 || '',
        audioUrl3: exerciseData.audioUrl3 || '',
        audioUrl4: exerciseData.audioUrl4 || ''
      }
      
      console.log('处理后的练习数据:', JSON.stringify(processedData, null, 2))
      
      // 保存数据到本地存储
      uni.setStorageSync('currentExerciseId', processedData.id)
      uni.setStorageSync('currentExerciseData', processedData)
      
      // 跳转到学习页面
      uni.switchTab({
        url: '/pages/study/index'
      })
    } else {
      throw new Error(res.data.message || '生成失败')
    }
  } catch (error) {
    console.error('生成题目失败:', error)
    uni.showToast({
      title: error.message || '生成失败',
      icon: 'none'
    })
  }
}

// 显示帮助
const showHelp = () => {
  uni.navigateTo({
    url: '/pages/guide/index'
  })
}
</script>

<style lang="scss" scoped>
.generate-page {
  min-height: 100vh;
  background: #fff;
  padding-bottom: calc(64px + env(safe-area-inset-bottom));
  padding-top: calc(48px + env(safe-area-inset-top));
}

.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding-top: env(safe-area-inset-top);
}

.nav-content {
  height: 48px;
  padding: 0 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.nav-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.help-btn {
  font-size: 14px;
  color: #2196f3;
  background: none;
  padding: 4px 12px 4px 8px;
  border: none;
  display: flex;
  align-items: center;
  margin-left: auto;
  margin-right: 8px;
  min-width: 64px;
  justify-content: flex-end;
  white-space: nowrap;
  
  &::after {
    display: none;
  }
  
  .iconfont {
    margin-right: 4px;
  }
}

.main-content {
  padding: 16px 20px;
}

.section {
  margin-bottom: 20px;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  .section-title {
    margin-bottom: 16px;
    font-size: 16px;
    color: #333;
    font-weight: 500;
  }

  &.first-section {
    margin-top: 8px;
  }
}

.input-methods {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;

  .method-item {
    height: 96px;
    background: #f8f9fa;
    border-radius: 12px;
    border: 1px solid #eee;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    padding: 12px;
    gap: 6px;

    &.active {
      background: linear-gradient(135deg, #2196F3, #1976D2);
      border: none;
      color: #fff;

      .desc {
        color: rgba(255, 255, 255, 0.8);
      }
    }

    .iconfont {
      font-size: 28px;
      margin-bottom: 4px;
    }

    .name {
      font-size: 15px;
    }

    .desc {
      font-size: 12px;
    }
  }
}

.char-input {
  height: 48px;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 0 16px;
  font-size: 16px;
  border: 1px solid #eee;
}

.unit-selector {
  display: flex;
  align-items: center;
  gap: 8px;

  button {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: #f8f9fa;
    border: 1px solid #eee;
    color: #666;
    font-size: 20px;
    line-height: 40px;
    transition: all 0.2s;

    &:active {
      background: #eee;
    }
  }

  .unit-input {
    flex: 1;
    height: 48px;
    background: #f8f9fa;
    border-radius: 12px;
    border: 1px solid #eee;
    text-align: center;
    font-size: 18px;
  }
}

.photo-area {
  aspect-ratio: 4/3;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #eee;
  overflow: hidden;
  margin-top: 8px;

  .preview {
    width: 100%;
    height: 100%;
  }

  .placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;

    .iconfont {
      font-size: 32px;
      margin-bottom: 8px;
    }

    .tip {
      font-size: 14px;
    }
  }
}

.difficulty-options,
.style-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;

  button {
    height: 44px;
    border-radius: 12px;
    background: #f8f9fa;
    border: 1px solid #eee;
    color: #666;
    font-size: 14px;
    line-height: 44px;
    padding: 0 8px;
    transition: all 0.2s;

    &.active {
      background: linear-gradient(135deg, #2196F3, #1976D2);
      border: none;
      color: #fff;
    }

    &:active {
      transform: scale(0.98);
    }
  }
}

.generate-btn-wrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 8px 20px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.05);
  height: 60px;
}

.generate-btn {
  height: 44px;
  background: linear-gradient(135deg, #2196F3, #1976D2);
  border-radius: 22px;
  color: #fff;
  font-size: 15px;
  font-weight: 600;
  transition: all 0.2s;

  &:active {
    transform: scale(0.98);
  }
}
</style> 